<!DOCTYPE html>
<html>

<head>
    {% load static %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>教师预约</title>

    <link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
    <link rel="stylesheet" href="{% static 'css/teacher_reserve.css' %}">

</head>

<body>
    <div class="layui-layout layui-layout-admin">
        <div class="layui-header">
            <div class="layui-logo layui-hide-xs layui-bg-black">智慧教室管理系统</div>
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item layui-hide layui-show-md-inline-block">
                    <a href="javascript:;">
                        <img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
                            class="layui-nav-img"> <span id="username"></span>
                    </a>
                    <dl class="layui-nav-child">
                        <dd><a href="/user_center/">个人中心</a></dd>
                        <dd><a href="">设置</a></dd>
                        <dd><a href="/login/">退出登录</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
                    <a href="javascript:;">
                        <i class="layui-icon layui-icon-more-vertical"></i>
                    </a>
                </li>
            </ul>
        </div>

        <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
            <ul class="layui-nav layui-nav-tree" lay-filter="test">
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="/teareserve/">教师预约</a>
                </li>
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="/teacher_attendance_index/">学生出勤管理</a>
                </li>
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="/table/">查看课表</a>
                </li>
            </ul>
        </div>
    </div>

        <div class="layui-body">

            <div class="basicInfoHeader">
                <p>教室预约</p>
            </div>
            <!-- 显示用户的预约记录 -->
            <div class="reserveRecord">
                <fieldset class="layui-elem-field">
                    <div>
                        <p style="text-align: center;">预约记录</p>
                    </div>
                    <div class="recordTableBox">
                        <table lay-filter="recordTable" id="recordTable">
                            <thead>
                                <tr>
                                    <th lay-data="{field:'id',fixed: 'center'}">预约ID</th>
                                    <th lay-data="{field:'building_name'}">预约楼栋</th>
                                    <th lay-data="{field:'classroom'}">预约教室</th>
                                    <th lay-data="{field:'time'}">预约时间</th>
                                    <th lay-data="{field:'remark'}">预约理由</th>
                                    <th lay-data="{field:'state'}">审核状态</th>
                                    <th lay-data="{field:'operation'}">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for reserve in reserves %}
                                {% if reserve.state == '待审核' %}
                                <tr>
                                    <td>{{reserve.reserve_id}}</td>
                                    <td>{{reserve.building_name}}</td>
                                    <td>{{reserve.classroom_id}}</td>
                                    <td>{{reserve.time}}</td>
                                    <td>{{reserve.remark}}</td>
                                    <td>{{reserve.state}}</td>
                                    <td>
                                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">撤销预约</a>

                                    </td>
                                </tr>
                                {% elif reserve.state == '已审核' %}
                                <tr>
                                    <td>{{reserve.reserve_id}}</td>
                                    <td>{{reserve.building_name}}</td>
                                    <td>{{reserve.classroom_id}}</td>
                                    <td>{{reserve.time}}</td>
                                    <td>{{reserve.remark}}</td>
                                    <td>{{reserve.state}}</td>
                                    <td>
                                        <button class="layui-btn layui-btn-sm revoke layui-btn-disabled" lay-event="recall">撤销预约</button>
                                    </td>
                                </tr>
                                {% else%}
                                <tr>
                                    <td>{{reserve.reserve_id}}</td>
                                    <td>{{reserve.building_name}}</td>
                                    <td>{{reserve.classroom_id}}</td>
                                    <td>{{reserve.time}}</td>
                                    <td>{{reserve.remark}}</td>
                                    <td ><span title="{{reserve.recall_remark}}">{{reserve.state}}</span></td>
                                    <td>
                                        <a class="layui-btn  layui-btn-xs delete"
                                            lay-event="again">再次预约</a>
                                        <!-- <button class="layui-btn layui-btn-sm delete">再次预约</button> -->
                                    </td>
                                </tr>
                                {%endif%}
                                {% endfor %}

                            </tbody>
                        </table>
                    </div>
                </fieldset>
            </div>

            <!-- selectBox中放的是选择层数、教室、提交、重置的盒子 -->
            <blockquote class="selectBox">
                <!-- 用一个表单，提交选择的楼层和教室 -->
                <div>
                    <p>
                        请选择教室和时间
                    </p>
                </div>
                <form class="layui-form" action="#" >
                    <!-- 选择楼栋 -->
                    <label class="layui-form-label">请选择楼栋</label>
                    <div class="layui-input-block floor">
                        <select name="building" id="rebuilding">
                            <option value="0"></option>
                            <option value="1">逸夫楼</option>
                            <option value="2">机电楼</option>
                            <option value="3">经管楼</option>
                            <option value="4">外语楼</option>
                        </select>
                    </div>
                    <!-- 选择楼层 -->
                    <label class="layui-form-label">请选择楼层</label>
                    <div class="layui-input-block floor">
                        <select name="floor" id="refloor">
                            <option value="0"></option>
                            <option value="1">一楼</option>
                            <option value="2">二楼</option>
                            <option value="3">三楼</option>
                            <option value="4">四楼</option>
                            <option value="5">五楼</option>
                        </select>
                    </div>
                    <!-- 选择教室 -->
                    <label class="layui-form-label">请选择教室</label>
                    <div class="layui-input-block room">
                        <select name="room" id="reroom">
                            <option value="0"></option>
                            <option value="1">01</option>
                            <option value="2">02</option>
                            <option value="3">03</option>
                            <option value="4">04</option>
                            <option value="5">05</option>
                        </select>
                    </div>
                    <label class="layui-form-label">请选择教学周</label>
                    <div class="layui-input-block week">
                        <select name="week" id="reweek">
                            <option value="0"></option>
                            <option value="1">01</option>
                            <option value="2">02</option>
                            <option value="3">03</option>
                            <option value="4">04</option>
                            <option value="5">05</option>
                            <option value="6">06</option>
                            <option value="7">07</option>
                            <option value="8">08</option>
                            <option value="9">09</option>
                            <option value="10">10</option>
                            <option value="11">11</option>
                            <option value="12">12</option>
                            <option value="13">13</option>
                            <option value="14">14</option>
                            <option value="15">15</option>
                            <option value="16">16</option>
                        </select>
                    </div>
                    <label class="layui-form-label">请选择日期</label>
                    <div class="layui-input-block day">
                        <select name="day" id="reday">
                            <option value="0"></option>
                            <option value="1">星期一</option>
                            <option value="2">星期二</option>
                            <option value="3">星期三</option>
                            <option value="4">星期四</option>
                            <option value="5">星期五</option>
                            <option value="6">星期六</option>
                            <option value="7">星期日</option>
                        </select>
                    </div>
                    <label class="layui-form-label" >请选择时间段</label>
                    <div class="layui-input-block time">
                        <select name="time" id="retime">
                            <option value="0"></option>
                            <option value="1">第1节</option>
                            <option value="2">第2节</option>
                            <option value="3">第3节</option>
                            <option value="4">第4节</option>
                            <option value="5">第5节</option>
                            <option value="6">第6节</option>
                        </select>
                    </div>
                    <label class="layui-form-label">请选择教室状态</label>
                    <div class="layui-input-block state">
                        <select name="state" id="restate">
                            <option value="0"></option>
                            <option value="1">空闲</option>
                            <option value="2">已预约</option>
                            <option value="3">正在使用</option>
                        </select>
                    </div>
                    <div class="layui-input-block submitReset">
                        <button type="button" class="layui-btn" id="searchBtn"  lay-filter="formDemo" data-type="reload">立即查询</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </form>
            </blockquote>

            <fieldset class="layui-elem-field">
                <div class="classroomTableBox">
                    <button type="button" class="layui-btn" id="reserve_all">一键预约</button>
                    <table class="layui-table"  id="useInfo_list" lay-filter="useInfoTable"></table>
{#                    <table lay-filter="classroomTable">#}
{#                        <thead>#}
{#                            <tr>#}
{#                                <th lay-data="{field:'',type:'checkbox', fixed: 'left'}"></th>#}
{#                                <th lay-data="{field:'building',fixed: 'center' }">楼栋</th>#}
{#                                <th lay-data="{field:'classroom',fixed: 'center'}">教室</th>#}
{#                                <th lay-data="{field:'week'}">教学周</th>#}
{#                                <th lay-data="{field:'day'}">日期</th>#}
{#                                <th lay-data="{field:'time'}">时间段</th>#}
{#                                <th lay-data="{field:'state'}">状态</th>#}
{#                                <th lay-data="{field:'operation'}">操作</th>#}
{#                            </tr>#}
{#                        </thead>#}
{#                        <tbody>#}
{#                            {% for classroomuserinfo in classroomuserinfos%}#}
{#                            <tr>#}
{#                                <td></td>#}
{#                                <td>{{classroomuserinfo.building}}</td>#}
{#                                <td>{{classroomuserinfo.cid}}</td>#}
{#                                <td>{{classroomuserinfo.week}}</td>#}
{#                                <td>{{classroomuserinfo.day}}</td>#}
{#                                <td>{{classroomuserinfo.time}}</td>#}
{#                                <td>{{classroomuserinfo.state}}</td>#}
{#                                <td>#}
{#                                    {% if classroomuserinfo.state == "空闲" %}#}
{#                                    <a class="layui-btn layui-btn-sm reserve" lay-event="reserve" onclick="reserveReason()">预约</a>#}
{#                                    {%else%}#}
{#                                    <button class="layui-btn layui-btn-sm layui-btn-disabled reserve">预约</button>#}
{#                                    {%endif%}#}
{#                                </td>#}
{#                            </tr>#}
{#                            {%endfor%}#}
{#                        </tbody>#}
{#                    </table>#}
                </div>
            </fieldset>
        </div>
    </div>

{#    填写预约的理由#}
<div id="reserveReason_main" style="display: none; ">
    <div class="layui-form " id="reserve-form ">
        <div class="layui-form-item center ">
            <label class="layui-form-label " style="width: 100px ">预约理由</label>
            <div class="layui-input-block ">
                <input type="text " id="reserve_reason_text" required value=" " style="width: 240px " lay-verify="required "
                       placeholder="请输入预约理由" autocomplete="off " class="layui-input ">
            </div>
        </div>
        <div class="layui-form-item ">
            <div class="layui-input-block ">
                <button class="layui-btn " lay-submit lay-filter="save" id="reserve_reason">立即提交</button>
            </div>
        </div>
    </div>
</div>

{#    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>#}

    <script src="{%static 'layui/layui.js'%}"></script>
    <script src="{%static 'jquery/jquery-3.2.1.js'%}"></script>
    <script src="{%static 'layer/layer.js'%}"></script>

    <script>
        function transday(text) {
            if (text == "星期一") {
                text = 1
            } else if (text == "星期二") {
                text = 2
            } else if (text == "星期三") {
                text = 3
            } else if (text == "星期四") {
                text = 4
            } else if (text == "星期五") {
                text = 5
            } else if (text == "星期六") {
                text = 6
            } else if (text == "星期日") {
                text = 7
            }
            return text
        }
        function transweek(text) {
            if (text == "第一周") {
                text = 1
            } else if (text == "第二周") {
                text = 2
            } else if (text == "第三周") {
                text = 3
            } else if (text == "第四周") {
                text = 4
            } else if (text == "第五周") {
                text = 5
            } else if (text == "第六周") {
                text = 6
            } else if (text == "第七周") {
                text = 7
            } else if (text == "第八周") {
                text = 8
            }
            return text
        }
        function transtime(text) {
            if (text == "第一节") {
                text = 1
            } else if (text == "第二节") {
                text = 2
            } else if (text == "第三节") {
                text = 3
            } else if (text == "第四节") {
                text = 4
            } else if (text == "第五节") {
                text = 5
            } else if (text == "第六节") {
                text = 6
            } else if (text == "第七节") {
                text = 7
            } else if (text == "第八节") {
                text = 8
            }
            return text
        }
        //JS
        var building=null,floor=null,room=null,week=null,day=null,time=null,state=null;
        layui.use(['element', 'layer', 'util', 'form', 'table'], function () {
        var element = layui.element,
            layer = layui.layer,
            util = layui.util,
            form = layui.form,
            table = layui.table,
            $ = layui.$;

        //头部事件
        util.event('lay-header-event', {
            //左侧菜单事件
            menuLeft: function (othis) {
                layer.msg('展开左侧菜单的操作', {
                    icon: 0
                });
            },
            menuRight: function () {
                layer.open({
                    type: 1,
                    content: '<div style="padding: 15px;">处理右侧面板的操作</div>',
                    area: ['260px', '100%'],
                    offset: 'rt' //右上角
                    ,
                    anim: 5,
                    shadeClose: true
                });
            }
        });

        //教室使用信息表格
        table.render({
            elem: "#useInfo_list",//赋值表格
            {#url:'/search_useInfo_new',//请求地址路由#}
            {#id:'alltable',#}
            loading: false,
            height: 312,
            page: true,
            limit:50,
            cols: [[
                {type: 'checkbox'},
                {field: "use_id", title: "使用信息ID" ,hide:true},
                {field: "building_id", title: "楼栋ID",hide:true},
                {field: "building_name", title: "楼栋"},
                {field: "cid", title: "教室"},
                {field: "week", title: "教学周"},
                {field: "day", title: "日期"},
                {field: "time", title: "时间段"},
                {field: "state", title: "状态"},
                {field: "capacity", title: "容量"},
                {field: "operation", title: "预约",
                    templet: function (row) {
                        if (row.state === '空闲') {
                            return  ' <a class="layui-btn layui-btn-sm reserve" lay-event="reserve">预约</a>';
                        } else return '<button class="layui-btn layui-btn-sm layui-btn-disabled reserve">预约</button>';
                    }
                }
            ]]
        })
        var table = layui.table;
        let ctrCheckArr = [];
        table.on('checkbox(useInfoTable)', function(obj){
            ctrCheckArr.length = 0;
            let checkStatus = table.checkStatus('useInfo_list')
            ctrCheckArr = checkStatus.data; //获取选中的数据
        });

        //转换静态表格
        table.init('recordTable', {
            height: 315,
            limit: 10,
            page: true
        });
        // 获得用户名
        $.ajax({
                url: "/user/",
                method: "get",
                success: function (response) {
                    if(response.msg === 'ok'){
                        $("#username").html(response.data.username)
                    } else {
                        window.location.href = '/login'
                    }
                },
                error: function (err) {
                    window.location.href = '/login'
                }
        })
            //更新表格
        function reload_table(building,floor,room,week,day,time,state) {
            table.reload('useInfo_list', {
                url: '/teareserve_search_useInfo_new/',
                method: "post",
                headers: {"X-CSRFToken": "{{ csrf_token }}"},
                page: true,
                where: {
                    "building": building,
                    "floor": floor,
                    "room": room,
                    "week": week,
                    "day": day,
                    "time": time,
                    "state": state
                },
                done: function (res, curr, count) {
                    if (!("flag" in res)) alert("未知错误");
                    else if (res["flag"] !== 0) alert(res["flag"]);
                    var states = "";
                     for (var i in res.data) {
                         var item = res.data[i];
                         if ((item.state !=="空闲")) {// 判断禁用的条件
                             // checkbox 根据条件设置不可选中
                             $('tr[data-index=' + i + '] input[type="checkbox"]').prop('disabled', true);
                             states = "1";// 隐藏表头全选判断状态
                             form.render();// 重新渲染一下
                         }
                     }
                     if(states === "1"){
                         // 禁用全选 checkbox
                         $('th[data-field='+0+'] input[type="checkbox"]').prop('disabled',true);
                     }
                     form.render('checkbox');
                }
            })
        }

        //点击查询按钮，查询使用信息,重载上方教室使用信息的表格
        $("#searchBtn").on("click", function () {
            {#console.log("表单提交");#}
            //检错
            building = $("#rebuilding").val();
            floor = $("#refloor").val();
            room = $("#reroom").val();
            week = $("#reweek").val();
            day = $("#reday").val();
            time = $("#retime").val();
            state = $("#restate").val();

            reload_table(building,floor,room,week,day,time,state);
        })
            //表格中，点击按钮，弹出预约理由的弹窗
        table.on("tool(useInfoTable)", function (obj) {
            if (obj.event === "reserve") {
                ctrCheckArr = [obj.data]
                //显示修改使用信息的弹窗
                index = layer.open({
                    type: 1,
                    title: "填写教室预约理由",
                    area: ['400px', '300px'],
                    shadeClose: true, //点击遮罩关闭
                    content: $("#reserveReason_main"),
                    success: function (layero, index) {
                    },
                    yes: function () {
                    }
                });
            }
        })

        table.on('tool(recordTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                layer.msg('ID：' + data.id + ' 的查看操作');
            } else if (obj.event === 'del') {
                layer.confirm('真的要撤销吗', function (index) {
                    obj.del();
                    $.ajax({
                        url: "/teareserve/",
                        method: "post",
                        data: {
                            id: data["id"],
                            datatype: "delete"
                        },
                        success: function (response) {
                        },
                        error: function (err) {

                        }
                    })
                    layer.close(index);
                });
            } else if (obj.event === 'again') {
                $.ajax({
                    url: "/teareserve/",
                    method: "post",
                    data: {
                        id: parseInt(obj.data['id']),
                        datatype: "update"
                    },
                    success: function (response) {
                        console.log(response);
                    },
                    error: function (err) {
                        console.log(err);
                    }
                })
                obj.update({
                    'state': '待审核',
                    'operation': '\n                                        <a class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\">撤销预约</a>\n\n'
                })
            } else if (obj.event === 'recall') {
                $.ajax({
                    url: "/teareserve/",
                    method: "post",
                    data: {
                       id: parseInt(obj.data['id']),
                        datatype: "delete"
                    },
                    success: function (response) {
                        console.log(response);
                    },
                    error: function (err) {

                    }
                })
                obj.del();
            }
        });
            //点击按钮，提交预约理由
        $("#reserve_reason").on("click", function () {
            var reason = $("#reserve_reason_text").val()
            if(!reason.trim()){
                alert("请填写预约理由");
                return
            }
            for(let data of ctrCheckArr){
                $.ajax({
                    url: "/teareserve/", //需补全
                    type: "post",
                    data: {
                        classroomid: data["classroom"],
                        week: transweek(data["week"]),
                        day: transday(data["day"]),
                        time: transtime(data["time"]),
                        datatype: "reserve",
                        remark: reason,
                        cid: data["ccid"],
                    },
                    dataType: "json",
                    headers: {"X-CSRFToken": "{{ csrf_token }}"},
                    success: function (res) {
                        var oldDatas = layui.table.cache['recordTable'];
                        if(oldDatas && oldDatas.length > 0 && oldDatas.filter(item=>parseInt(item.id)===res.data.id).length > 0){
                            let f = oldDatas.filter(item=>parseInt(item.id)===res.data.id)[0]
                            f['remark'] = res.data["remark"]
                            f['state'] = "待审核"
                            f['operation'] = '\n  <a class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\">撤销预约</a>\n\n'
                        } else {
                            var newData = res.data;
                            newData['operation']= '\n  <a class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\">撤销预约</a>\n\n'
                            oldDatas.push(newData);
                        }

                        table.reload('recordTable', {
                            data : oldDatas,
                        })
                        //关闭弹窗更新表格
                        layer.close(layer.index);
                        reload_table(building,floor,room,week,day,time,state);
                    },
                    error: function () {
                        alert("ajax请求错误");
                    }
                })
            }
            ctrCheckArr = []

        })
            //点击按钮，提交预约理由
        $("#reserve_all").on("click", function () {
            //显示修改使用信息的弹窗
            index = layer.open({
                type: 1,
                title: "填写教室预约理由",
                area: ['400px', '300px'],
                shadeClose: true, //点击遮罩关闭
                content: $("#reserveReason_main"),
                success: function (layero, index) {
                },
                yes: function () {
                }
            });
        })

    });
    </script>
<script>
    //判断当前登录的是谁
    $.ajax({
                url: "/user/",
                method: "get",
                success: function (response) {
                    if(response.msg === 'ok'){
                        $("#username").html(response.data.username)
                    } else {
                        window.location.href = '/login'
                    }
                },
                error: function (err) {
                    window.location.href = '/login'
                }
        })
</script>
</body>

</html>